package com.slm.krstartimes.activity;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.karumi.expandableselector.ExpandableItem;
import com.karumi.expandableselector.ExpandableSelector;
import com.karumi.expandableselector.ExpandableSelectorListener;
import com.karumi.expandableselector.OnExpandableItemClickListener;
import com.slm.krstartimes.R;
import com.slm.krstartimes.adapter.FragmentAdapter;
import com.slm.krstartimes.db.sqlite.SQLiteDataBaseTools;
import com.slm.krstartimes.fragment.AndroidHomeFragment;
import com.slm.krstartimes.fragment.DigitalHomeFragment;
import com.slm.krstartimes.fragment.IOSHomeFragment;
import com.slm.krstartimes.fragment.MainMenuFragment;
import com.slm.krstartimes.fragment.PhoneNewsFragment;
import com.slm.krstartimes.fragment.RecommendPageFragment;
import com.slm.krstartimes.fragment.WPHomeFragment;
import com.slm.krstartimes.fragment.WindowsHomeFragment;
import com.slm.krstartimes.utils.MyImageLoader;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends FragmentActivity implements View.OnTouchListener, GestureDetector.OnGestureListener {
    public static RequestQueue requestQueue;
    public static SQLiteDataBaseTools sqLiteDataBaseTools;
    public static ImageLoader imageLoader;
    private ViewPager viewPager;
    private TabLayout tabLayout;
    private FragmentAdapter fragmentAdapter;
    private ExpandableSelector iconsExpandableSelector;
    private Handler handler;
    private Context context;
    private long exitTime = 0;
    private FrameLayout main_layout;
    private GestureDetector mGestureDetector;
    private int verticalMinDistance = 30;
    private int middleDistance = 150;
    private int minVelocity = 0;
    private LinearLayout list;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY, "jMg41lkYhwWlykI0PUiQoj12");
        setContentView(R.layout.activity_main);// 加载布局

        initView();

//        Intent intent = new Intent(this, NotificationService.class);// 开启推送服务
//        startService(intent);
        viewPager.setOffscreenPageLimit(0);
        List<Fragment> datas = new ArrayList<>();// 加载fragment

        datas.add(new MainMenuFragment());
        Bundle args = new Bundle();
        new MainMenuFragment().setArguments(args);

        datas.add(new RecommendPageFragment());
        datas.add(new PhoneNewsFragment());
        datas.add(new AndroidHomeFragment());
        datas.add(new IOSHomeFragment());
        datas.add(new WPHomeFragment());
        datas.add(new DigitalHomeFragment());
        datas.add(new WindowsHomeFragment());

        String[] titles = getResources().getStringArray(R.array.title);

        fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), datas, titles);
        viewPager.setAdapter(fragmentAdapter);//绑定内容
        tabLayout.setTabsFromPagerAdapter(fragmentAdapter);//绑定标题
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.getTabCount();
        initializeIconsExpandableSelector();

    }

    /**
     * 初始化方法
     */
    private void initView() {
        requestQueue = Volley.newRequestQueue(this);

        imageLoader = new ImageLoader(requestQueue, new MyImageLoader());

        sqLiteDataBaseTools = new SQLiteDataBaseTools(MainActivity.this);

        viewPager = (ViewPager) findViewById(R.id.mainviewPager);//实例化组件
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        main_layout = (FrameLayout) findViewById(R.id.main_layout);
        main_layout.setOnTouchListener(this);
        mGestureDetector = new GestureDetector(this);
    }

    /**
     * 菜单键
     */
    private void initializeIconsExpandableSelector() {
        iconsExpandableSelector = (ExpandableSelector) findViewById(R.id.es_icons);
        List<ExpandableItem> expandableItems = new ArrayList<ExpandableItem>();
        ExpandableItem item = new ExpandableItem();
        item.setResourceId(R.mipmap.up);
        expandableItems.add(item);
        item = new ExpandableItem();
        item.setResourceId(R.mipmap.process);
        expandableItems.add(item);
        item = new ExpandableItem();
        item.setResourceId(R.mipmap.search);
        expandableItems.add(item);
        item = new ExpandableItem();
        item.setResourceId(R.mipmap.female_user);
        expandableItems.add(item);
        iconsExpandableSelector.showExpandableItems(expandableItems);
        iconsExpandableSelector.setOnExpandableItemClickListener(new OnExpandableItemClickListener() {
            /**
             * 选项监听
             * @param index
             * @param view
             */
            @Override
            public void onExpandableItemClickListener(int index, View view) {
                if (index == 0 && iconsExpandableSelector.isExpanded()) {
                    iconsExpandableSelector.collapse();
                    updateIconsFirstButtonResource(R.mipmap.up);
                }
                switch (index) {
                    case 1:
                        showToast("设置");
                        Intent intent1 = new Intent();
                        intent1.setClass(MainActivity.this, SettingActivity.class);
                        startActivity(intent1);
                        break;
                    case 2:
                        showToast("搜索");
                        Intent intent2 = new Intent();
                        intent2.setClass(MainActivity.this, SearchActivity.class);
                        startActivity(intent2);
                        break;
                    case 3:
                        showToast("个人中心");
                        Intent intent3 = new Intent();
                        intent3.setClass(MainActivity.this, PersonCenterActivity.class);
                        startActivity(intent3);
                        break;
                    default:
                }
            }
        });
        iconsExpandableSelector.setExpandableSelectorListener(new ExpandableSelectorListener() {
            @Override
            public void onCollapse() {

            }

            @Override
            public void onExpand() {
                updateIconsFirstButtonResource(R.mipmap.down);
            }

            @Override
            public void onCollapsed() {

            }

            @Override
            public void onExpanded() {

            }
        });
    }

    private void updateIconsFirstButtonResource(int resourceId) {
        ExpandableItem arrowUpExpandableItem = new ExpandableItem();
        arrowUpExpandableItem.setResourceId(resourceId);
        iconsExpandableSelector.updateExpandableItem(0, arrowUpExpandableItem);
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 双击退出方法
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float v, float v1) {

        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    /**
     * 滑动隐藏菜单键
     *
     * @param e1
     * @param e2
     * @param v
     * @param v1
     * @return
     */
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float v, float v1) {
        if (e1.getY() - e2.getY() > minVelocity) {
            iconsExpandableSelector.setVisibility(View.INVISIBLE);
            Animation animation1 = AnimationUtils.loadAnimation(this, R.anim.alpha_a);
            iconsExpandableSelector.setAnimation(animation1);
        }
        if (e2.getY() - e1.getY() > minVelocity) {
            iconsExpandableSelector.setVisibility(View.VISIBLE);
            Animation animation2 = AnimationUtils.loadAnimation(this, R.anim.alpha_b);
            iconsExpandableSelector.setAnimation(animation2);

        }
        return false;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        mGestureDetector.onTouchEvent(ev);
        // scroll.onTouchEvent(ev);
        return super.dispatchTouchEvent(ev);
    }

}
